\<template>
  <div style="padding: 5px 20px;">
    <br>
    <el-form :inline="true" :model="listQuery" class="demo-form-inline">
      <el-form-item label="提交者ID">
        <el-input v-model="listQuery.submitter_id" placeholder="请输入提交者ID"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">
          <template #icon>
            <el-icon><Search /></el-icon>
          </template>
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="TJCollectionForm">
          <template #icon>
            <el-icon><Edit /></el-icon>
          </template>
          添加
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 表格-->
    <el-table :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label="提交者ID" prop="submitter_id" width="100"></el-table-column>
      <el-table-column label="注册时间">
        <template v-slot="scope">
          <el-icon><Clock /></el-icon>&nbsp;
          <span style="margin-left: 5px">{{ formatDateTime(scope.row.register_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后操作时间">
        <template v-slot="scope">
          <el-icon><Clock /></el-icon>&nbsp;
          <span style="margin-left: 5px">{{ formatDateTime(scope.row.last_operation_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交工单数" prop="submitted_tickets"></el-table-column>
      <el-table-column label="标记" prop="flag"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template v-slot="scope">
          <el-tooltip class="item" effect="dark" content="修改" placement="top">
            <el-button type="primary" circle @click="BJCollectionForm(scope.$index)">
              <el-icon><Edit /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <el-button type="danger" circle @click="deleteVisible(scope.row)">
              <el-icon><Delete /></el-icon>
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
                   :page-sizes="[10]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
                   :background="true">
    </el-pagination>

    <el-dialog :title="textMap[dialogStatus]" v-model="dialogFormVisible">
      <el-form ref="collectionform" :rules="rules" :model="ruleForm" label-width="120px" label-position="left">
        <el-form-item label="提交者ID" prop="submitter_id" v-if="dialogStatus=='create'">
          <el-input placeholder="提交者ID" v-model="ruleForm.submitter_id"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="submitter_pass">
          <el-input placeholder="密码" v-model="ruleForm.submitter_pass"></el-input>
        </el-form-item>
        <el-form-item label="注册时间" prop="register_time">
          <el-date-picker
            v-model="ruleForm.register_time"
            type="datetime"
            placeholder="选择注册时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最后操作时间" prop="last_operation_time">
          <el-date-picker
            v-model="ruleForm.last_operation_time"
            type="datetime"
            placeholder="选择最后操作时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="提交工单数" prop="submitted_tickets">
          <el-input placeholder="提交工单数" v-model="ruleForm.submitted_tickets" type="number"></el-input>
        </el-form-item>
        <el-form-item label="标记" prop="flag">
          <el-input placeholder="标记" v-model="ruleForm.flag" type="number"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" v-if="dialogStatus=='create'" @click="submitCollectionForm('collectionform')">添 加</el-button>
        <el-button type="warning" v-else @click="updateCollectionForm('collectionform')">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Edit, Clock, Delete } from '@element-plus/icons-vue';
import { ref } from 'vue';
import axios from 'axios';

export default {
  name: 'Submitters',
  components: {
    Search,
    Edit,
    Clock,
    Delete
  },
  mounted() {
    this.fetchData();
  },
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: 10,
        submitter_id: '',
      },
      dialogFormVisible: false,
      dialogStatus: 'create',
      textMap: {
        update: '修改提交者',
        create: '添加提交者'
      },
      ruleForm: {
        submitter_id: '',
        submitter_pass: '',
        register_time: '',
        last_operation_time: '',
        submitted_tickets: 0,
        flag: 0,
      },
      rules: {
        submitter_id: [{
          required: true,
          message: '请输入提交者ID',
          trigger: 'blur'
        }],
        submitter_pass: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }],
        register_time: [{
          required: true,
          message: '请选择注册时间',
          trigger: 'blur'
        }],
        last_operation_time: [{
          required: true,
          message: '请选择最后操作时间',
          trigger: 'blur'
        }],
        submitted_tickets: [{
          required: true,
          message: '请输入提交工单数',
          trigger: 'blur'
        }],
        flag: [{
          required: true,
          message: '请输入标记',
          trigger: 'blur'
        }]
      }
    };
  },
  methods: {
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      axios.get('http://127.0.0.1:8000/qa/submitters/', {
        params: {
          page: this.listQuery.page,
          limit: this.listQuery.limit,
          keyword: this.listQuery.submitter_id
        }
      }).then(response => {
        this.listLoading = false;
        this.list = response.data.results;
        this.total = response.data.count;
      }).catch(error => {
        console.error('Error fetching data:', error);
        this.listLoading = false;
      });
    },
    TJCollectionForm() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        console.log('dialogFormVisible:', this.dialogFormVisible);
      });
    },
    resetForm() {
      this.ruleForm = {
        submitter_id: '',
        submitter_pass: '',
        register_time: '',
        last_operation_time: '',
        submitted_tickets: 0,
        flag: 0,
      };
    },
    BJCollectionForm($index) {
      this.ruleForm = JSON.parse(JSON.stringify(this.list[$index]));
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },
    submitCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.post('http://127.0.0.1:8000/qa/add-scenic-spot/', this.ruleForm).then(response => {
            this.fetchData();
            console.log(response)
            this.dialogFormVisible = false;
            this.$message.success('添加数据成功！');
          }).catch(error => {
            console.error('Error submitting data:', error);
            this.$message.error('添加数据失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    updateCollectionForm(formname) {
      this.$refs[formname].validate((valid) => {
        if (valid) {
          axios.put(`http://127.0.0.1:8000/qa/update_submitter/${this.ruleForm.submitter_id}/`, this.ruleForm).then(response => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$message.success('修改数据成功！');
          }).catch(error => {
            console.error('Error updating data:', error);
            this.$message.error('修改数据失败！');
          });
        } else {
          console.log('error submit!');
          return false;
        }
      });
    },
    deleteVisible(scope) {
      const csrfToken = this.$cookies.get('csrftoken');
      if (!csrfToken) {
        console.error('CSRF token not found');
        this.$message.error('CSRF token not found');
        return;
      }

      this.$confirm(`确定要删除 ${scope.submitter_id} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const url = `http://127.0.0.1:8000/qa/delete_submitter/${scope.submitter_id}/`;
        this.$axios.delete(url, { withCredentials: true, headers: { 'X-CSRFToken': csrfToken } })
          .then(response => {
            this.fetchData();
            this.$message.success('删除成功');
          })
          .catch(error => {
            console.error('Error:', error);
            this.$message.error('删除数据失败！请检查网络连接或重试。');
            if (error.response && error.response.status === 403) {
              this.$message.error('CORS 策略阻止了请求。请检查后端配置。');
            }
          });
      }).catch(() => {
        // 用户取消删除
      });
    },
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
}
</script>
<style>
.answer-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
